package org.jetlinks.pro.clickhouse.engine;

import lombok.Getter;
import lombok.Setter;
import org.hswebframework.web.bean.FastBeanCopier;
import org.springframework.util.StringUtils;

import java.util.StringJoiner;

@Getter
@Setter
public class Distributed implements Engine {

    private String cluster;

    private String database;

    private String shardingKey;

    private String table;
    @Override
    public boolean isDistributed() {
        return true;
    }

    @Override
    public String buildCreateTableSql(String table, String... columns) {

        StringJoiner ddl = new StringJoiner("\n");
        ddl.add("CREATE TABLE IF NOT EXISTS " + table);
        ddl.add(" ON CLUSTER " + cluster);

        StringJoiner columnSQL = new StringJoiner(",\n", "(", ")");
        for (String column : columns) {
            columnSQL.add(column);
        }
        ddl.add(columnSQL.toString());

        StringJoiner engine = new StringJoiner(",", " ENGINE = Distributed(", ")");
        engine.add(this.cluster);
        engine.add(this.database);
        engine.add(this.table);
        if (StringUtils.hasText(shardingKey)) {
            engine.add(shardingKey);
        }
        ddl.add(engine.toString());
        return ddl.toString();
    }

    public Distributed cluster(String cluster) {
        setCluster(cluster);
        return this;
    }

    public Distributed database(String database) {
      setDatabase(database);
        return this;
    }

    public Distributed table(String table) {
        setTable(table);
        return this;
    }

    public Distributed shardingKey(String shardingKey) {
        setShardingKey(shardingKey);
        return this;
    }

    public Distributed copy(){
        return FastBeanCopier.copy(this, new Distributed());
    }

}

